
type DataType = 'data' |'sessionStorage'|'localStorage'

class GlobalData {
	constructor(props: any) {
		const { data, sessionData, localData } = props;
		this._data = data;
		this.sessionData = { ...sessionData, ...this.getDataInSession() };
		this.localData = { ...localData, ...this.getDataInLocal() };
		window.sessionStorage.setItem('_data', JSON.stringify(this.sessionData));
		window.localStorage.setItem('_data', JSON.stringify(this.localData));
	}
	_data: any = {};
	sessionData = {};
	localData = {};
	getItem(item: string) {
		return this._data[item]
	}
	checkInit(item: string, type: DataType) {
		let data: any = {};
		switch (type) {
			case 'data':
				data = this._data
				break;
			case 'sessionStorage':
				data = this.sessionData
				break;
			case 'localStorage':
				data = this.localData
				break;
			default:
				break;
		}
		if (typeof data[item] === 'undefined') {
			throw (new Error('请在初始化的时候配置此参数'))
		} else {
			return true;
		}

	}
	setItem(item: string, value: string) {
		if (this.checkInit(item, 'data')) {
			this._data[item] = value;
		}
	}
	getItemInSession(item: string) {
		return (this.getDataInSession() as any)[item]
	}
	setItemInSession(item: string, value: string) {
		if (this.checkInit(item, 'sessionStorage')) {
			window.sessionStorage.setItem('_data', JSON.stringify({ ...this.getDataInSession(), [item]: value }))
		}
	}
	getItemInLocal(item: string) {
		return (this.getDataInLocal() as any)[item]
	}
	setItemInlocal(item: string, value: string) {
		if (this.checkInit(item, 'localStorage')) {
			window.localStorage.setItem('_data', JSON.stringify({ ...this.getDataInLocal(), [item]: value }))
		}
	}
	getDataInSession() {
		let _data = {}
		try {
			_data = JSON.parse(window.sessionStorage.getItem('_data') as string)
		} catch (error) {

		}
		return _data;
	}
	getDataInLocal() {
		let _data = {}
		try {
			_data = JSON.parse(window.localStorage.getItem('_data')as string)
		} catch (error) {

		}
		return _data;
	}
}
const globalData = new GlobalData({
	data: {
		billType: 'bill',
		contractModifyFields:[],
		listContractSignTemplates: [],
	},
	sessionData: {
		billIdList: JSON.stringify([]),
	},
	localData: {
		showOfAlert: 1,
		thirdCustomer: {},
	},

})

export default globalData;
